package com.woniuxy.mqconsumer.mqlistener;

import com.rabbitmq.client.Channel;
import com.woniuxy.mqconsumer.entity.EsBook;
import com.woniuxy.mqconsumer.service.EsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@RabbitListener(queues = "es_queue")
@Slf4j
public class EsListener {
    @Autowired
    EsService esService ;

    @RabbitHandler
    public void onMsg(Map<String, Object> msg, Channel channel, Message message) throws IOException {
        try {
            Long bookId = (Long) msg.get("bookId");
            //根据图书的ID 查询一个 EsBooK对象
            EsBook esBook = esService.findEsBookByKey(bookId);
            //同步所用库
            esService.saveEsBookToIndex(esBook);
            //手动回应ack  1. 参数 1 ，获取当前消息的序号  参数 2 ，true  应答 比本消息序号小的 所有消息 false  应该本消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("消息消费失败 -->"+msg);
            /**
             * 拒绝确认消息:<br>
             * channel.basicNack(long deliveryTag, boolean multiple, boolean requeue) ; <br>
             * deliveryTag:该消息的index<br>
             * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。<br>
             * requeue：被拒绝的是否重新入队列 <br>
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                    false, true);
        }
    }
}
